import { type Model } from 'mongoose';
import { CreateUserDto, UpdateUserDto, User, UserDocument } from '@ai/entity';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { ROLE_MENU } from '@/common/config/role.menu';
import { getHash } from '@/utils/hash';
import { RoleService } from '../role/role.service';

@Injectable()
export class UserService implements OnModuleInit {
    constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}

    onModuleInit() {
        this.userModel.init();
    }

    async create(createUserDto: CreateUserDto) {
        // const defaultRole = await this.roleService.findOneByName(ROLE_MENU.USER);
        // const roles = [defaultRole._id];
        const password = getHash(createUserDto.password);
        const createdUser = new this.userModel(Object.assign(createUserDto, { password }));
        const user = await createdUser.save();
        user.password = null; // 除了查询，其他操作都会返回密码，则需手动去除
        return user;
    }

    async findAll(): Promise<User[]> {
        return this.userModel.find().populate('roles', '', 'Role').exec();
    }

    async findOne(updateUserDto: UpdateUserDto): Promise<UserDocument> {
        return await this.userModel.findOne(updateUserDto).populate('roles', '', 'Role').exec();
    }

    async findOneById(id: string): Promise<User> {
        return await this.userModel.findById(id).populate('roles', '', 'Role').exec();
    }

    async findByIdAndUpdate(id: string, updateUserDto: UpdateUserDto): Promise<User> {
        return this.userModel.findByIdAndUpdate(id, updateUserDto, { new: true }).exec();
    }

    async deleteById(id: string): Promise<User> {
        return this.userModel.findByIdAndDelete(id).exec();
    }

    async getUserRoleById(id: string) {
        const { roles } = await this.userModel.findById(id).select('roles').populate('roles', '', 'Role').exec();
        if (roles?.length === 0) return [];
        return roles.map((role) => role.name);
    }
}
